package com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.realm;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.entity.SysUser;
import com.llmcu.source.mybatisplus.officialsample.quickstart.shiro.mapper.SysUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * xxxx
 *
 * @author liuling
 * @date 2024-12-30 17:46
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private SysUserMapper userMapper;
    // 自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 自定义认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1.获取用户身份信息
        String name = token.getPrincipal().toString();
        // 2.数据库用户信息
        SysUser sysUser = userMapper.selectOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getName, name));
        // 3.用户存在时封装返回
        if(Objects.nonNull(sysUser)){

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    sysUser.getPassword(),
                    ByteSource.Util.bytes("customSaltValue"),
                    token.getCredentials().toString()
            );
            return info;
        }
        return null;
    }
}
